<template>
  <view>
    <van-cell-group>
      <van-cell center title="新增通讯录" use-label-slot>
        <view slot="right-icon">
          <i class="i-ic:twotone-plus c-color w-8 h-8" @click="addContact()"></i>
        </view>
      </van-cell>
    </van-cell-group>
    <view class="mt-2 bg-white">
      <view v-for="(item, index) in state.phoneArr" :key="index" class="flex items-center">
        <view class="w-98%">
          <van-cell-group inset>
            <van-field :value="item.linkName" placeholder="请输入联系人姓名" :label="'联系人' + (index + 1)" clearable @change="item.linkName = $event.detail" />
            <van-field :value="item.linkPhone" placeholder="请输入联系电话" :border="false" label="联系电话" clearable @change="item.linkPhone = $event.detail" />
          </van-cell-group>
        </view>
        <view class="w-12%">
          <i class="i-ep:delete w-6 h-6 c-red-6" @click="delContact(index)"></i>
        </view>
      </view>
    </view>
    <view class="w-full fixed c-pd" :style="{ bottom: `${store.$state.systemInfo.safeAreaInsets!.bottom}px` }">
      <van-button type="primary" block @click="handleSubmit">保存</van-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import useModal from '@/hooks/useModal';
import EquipRequest from '@/request/equipRequest';
import { useAppStore } from '@/store';

interface IProps {
  equipId: number;
  equipType: number;
}

const { showModal } = useModal();

const store = useAppStore();

const props = defineProps<IProps>();

interface IState {
  phoneArr: {
    linkName: string;
    linkPhone: string;
  }[];
  equipId: number;
  equipType: number;
}
const state = reactive<IState>({
  phoneArr: [
    {
      linkName: '',
      linkPhone: '',
    },
  ],
  equipId: 0,
  equipType: 1, //呼叫器2 其他类型1
});

onMounted(() => {
  state.equipId = props.equipId;
  state.equipType = props.equipType;
  getContact();
});

const addContact = () => {
  if (state.equipType === 2) {
    if (state.phoneArr.length === 4) {
      showModal('最多只可以添加四个');
      return false;
    }
  } else {
    if (state.phoneArr.length === 5) {
      showModal('最多只可以添加五个');
      return false;
    }
  }
  let obj = {
    linkName: '',
    linkPhone: '',
  };
  state.phoneArr.push(obj);
};

const delContact = (index: number) => {
  if (state.phoneArr.length === 1) {
    showModal('至少保留一个联系人');
    return false;
  }
  state.phoneArr.splice(index, 1);
};

const getContact = () => {
  EquipRequest.GetContact({
    equipId: state.equipId,
    hasLoading: true,
  }).then((res) => {
    if (!res.data || !res.data.linkNames) return;
    let { linkNames, linkPhones } = res.data;
    if (linkNames) {
      let namesArray: string[] = linkNames.split(',');
      let phonesArray: string[] = linkPhones.split(',');
      namesArray.forEach((item, index) =>
        state.phoneArr.push({
          linkName: item,
          linkPhone: phonesArray[index],
        }),
      );
    }
  });
};

const checkData = () => {
  const { phoneArr } = state;
  const phoneReg = /^\d+$/;
  if (!phoneArr.length) {
    showModal('至少填写一个联系人和联系电话');
    return;
  }
  for (let index in phoneArr) {
    if (!phoneArr[index].linkName) {
      showModal('请输入联系人');
      return;
    }
    if (!phoneArr[index].linkPhone) {
      showModal('请输入联系电话');
      return;
    }

    if (phoneArr[index].linkPhone && !phoneReg.test(phoneArr[index].linkPhone)) {
      showModal(`第${Number(index) + 1}个电话号码格式错误`);
      return;
    }
  }
  return true;
};

const handleSubmit = () => {
  if (!checkData()) return;
  showModal('确定保存').then(() => {
    const { phoneArr, equipId } = state;
    let linkNames: string[] = [];
    let linkPhones: string[] = [];
    phoneArr.forEach((item) => linkNames.push(item.linkName) && linkPhones.push(item.linkPhone));
    const params = {
      equipId,
      linkNames: linkNames.toString(),
      linkPhones: linkPhones.toString(),
    };
    EquipRequest.SetContact(params)
      .then((res) => {
        if (res.status === 0) {
          showModal('设置成功');
          setTimeout(() => {
            getContact();
          }, 1000);
        } else {
          showModal(res.msg);
        }
      })
      .catch((err) => {
        showModal(err.msg);
      });
  });
};
</script>
